package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"practice-one/models/mysql"
	"practice-one/pkg"

	"practice-one/userrpc/internal/svc"
	"practice-one/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *userrpc.UserRegisterRequest) (*userrpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line

	var findUser mysql.User
	if err := findUser.FindUserByTel(mysql.DB, in.Tel); err != nil {
		return nil, err
	}
	if findUser.ID != 0 {
		return nil, errors.New("该手机号已注册")
	}

	user := &mysql.User{
		Tel:       in.Tel,
		Password:  pkg.Md5(in.Password),
		HeadImage: "http://t4kaqyl71.hn-bkt.clouddn.com/QQ20251023-153421.png",
		NickName:  fmt.Sprintf("用户%d", rand.Intn(10000)),
	}
	if err := user.UserAdd(mysql.DB); err != nil {
		return nil, err
	}
	return &userrpc.UserRegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
